package com.baoteng.captcha.recognition.controller;

import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baoteng.captcha.recognition.service.impl.PicsCaptchaService;
import com.baoteng.captcha.recognition.service.impl.PinganCaptchaService;
import com.baoteng.captcha.recognition.service.impl.WhiteListServices;
import com.baoteng.captcha.recognition.vo.CaptchaVO;
import com.baoteng.captcha.recognition.vo.RecognizeResultVO;
import com.google.common.collect.Lists;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/c/r")
@Api("验证码API")  
public class ApiController {

	private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

//	@Autowired
//	private RedisTemplate<String, Object> objectRedisTemplate;
//
//	@Autowired
//	private RedisTemplate<String, Object> jsonRedisTemplate;

	@Autowired
	PicsCaptchaService picsCaptchaService;
	
	@Autowired
	PinganCaptchaService pinganCaptchaService;
	
	@Autowired
	WhiteListServices whiteListService;
	
	/**
	 * 平安续保查询验证码测试
	 * @param captcha
	 * @return
	 */
	@ApiOperation("识别平安续保查询验证码")
	@ApiImplicitParams({@ApiImplicitParam(paramType="query",name="captcha",dataType="CaptchaVO",required=true,value="验证码对象")})
	@ApiResponses({  
        @ApiResponse(code=500,message="图片数据过大"),  
        @ApiResponse(code=404,message="数据为空")  
    }) 
	@RequestMapping(value = { "/pa/q" }, method = RequestMethod.POST)
	public CaptchaVO recognizePA(@RequestBody CaptchaVO captcha) {
		if (captcha == null || StringUtils.isBlank(captcha.getData())) {
			return initReturnMsg(captcha,"404", "data is empty");
		}
		if(captcha.getData().length()>10*1024){
			return initReturnMsg(captcha,"500", "data too long");
		}
		String result = pinganCaptchaService.recognizeQueryCaptcha(Base64.decodeBase64(captcha.getData()));
		if(result==null || result.length()!=4 ){
			logger.info("pa query captcha fail.data-[{}],result-[{}]",captcha.getData(),result);
			return initReturnMsg(captcha,"404", "fail");
		}
		logger.info("pa query captcha succ.result-[{}]",result);
		initReturnMsg(captcha,"0", "succ");
		captcha.setData(null);
		captcha.setText(result);
		return captcha;
	}

	/**
	 * 平安续保查询验证码测试
	 */
	@RequestMapping(value = { "/pa/q/test"}, method = {RequestMethod.POST,RequestMethod.GET})
	public CaptchaVO recognizePATest() {
		CaptchaVO result = null;
		try {
			result = pinganCaptchaService.test();
		} catch (Exception e) {
			e.printStackTrace();
			return new CaptchaVO("500", e.getMessage());
		}
		if(result==null || !"0".equals(result.getCode())){
			logger.info("test pics query captcha fail.data-[{}],result-[{}]",result!=null?result.getData():null,result!=null?result.getText():null);
			return new CaptchaVO("404", "fail");
		}
		logger.info("test pics query captcha succ.result-[{}]",result.getText());
		return result;
	}

	/**
	 * 中保信验证码
	 */
	@RequestMapping(value = { "/pics/q"}, method = RequestMethod.POST)
	public RecognizeResultVO recognizePICS(@RequestBody List<CaptchaVO> captcha) {
		
		if (captcha == null || captcha.isEmpty()) {
			return new RecognizeResultVO("404", "data is empty");
		}
		if(captcha.size()>10){
			return new RecognizeResultVO("500", "data length limit is 10");
		}
		
		List<CaptchaVO> data = Collections.synchronizedList(Lists.newArrayList());
		captcha.parallelStream().forEach((c) -> {
			logger.info("pics receive,incode-[{}],vehicle-[{}],name-[{}]",c.getInsurecode(),c.getVeCode(),c.getName());
			if(c.getData().length()>10*1024) {
				data.add(initReturnMsg(c,"500", "data too long"));
				return ;
			}
			
			String result = whiteListService.getCaptchaVo(c);
			if(StringUtils.isBlank(result)) {
				try {
					result = picsCaptchaService.recognize(Base64.decodeBase64(c.getData()),null);
					CaptchaVO cv = new CaptchaVO();
					BeanUtils.copyProperties(c, cv);
					cv.setText(result);
					whiteListService.saveCaptchaVo(cv);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			if(result==null || result.length()!=4 ){
				logger.info("pics query captcha fail.data-[{}],result-[{}]",c.getData(),result);
				data.add(initReturnMsg(c,"1", "fail"));
				return ;
			}
			logger.info("pics query captcha succ.result-[{}],incode-[{}],vehicle-[{}]",result,c.getInsurecode(),c.getVeCode());
			c.setCode("0");
			c.setData(null);
			c.setMsg("succ");
			c.setText(result);
			data.add(c);
		});
		RecognizeResultVO result = new RecognizeResultVO("0","ok");
		result.setCaptcha(data);
		return result;
	}
	
	private CaptchaVO initReturnMsg(CaptchaVO vo,String code,String msg){
		vo.setCode(code);
		vo.setMsg(msg);
		return vo;
	}
	
	/**
	 * 中保信验证码测试
	 */
	@RequestMapping(value = { "/pics/q/test"}, method = {RequestMethod.POST,RequestMethod.GET})
	public RecognizeResultVO recognizePICSTest() {
		CaptchaVO _vo = null;
		try {
			_vo = picsCaptchaService.test();
		} catch (Exception e) {
			e.printStackTrace();
			return new RecognizeResultVO("500", e.getMessage());
		}
		if(_vo==null || !"0".equals(_vo.getCode())){
			logger.info("test pics query captcha fail.data-[{}],result-[{}]",_vo!=null?_vo.getData():null,_vo!=null?_vo.getText():null);
			return new RecognizeResultVO("404", "fail");
		}
		logger.info("test pics query captcha succ.result-[{}]",_vo.getText());
		RecognizeResultVO result = new RecognizeResultVO("0", "succ") ;
		result.setCaptcha(Lists.newArrayList(_vo));
		return result;
	}
	
	/**
	 * 中保信验证码测试
	 */
	@RequestMapping(value = { "/test/fb"}, method = {RequestMethod.POST,RequestMethod.GET})
	public CaptchaVO feedback(HttpServletRequest httpRequest) {
		if(StringUtils.isBlank(httpRequest.getParameter("c"))){
			return new CaptchaVO("500","invalid data");
		}
		logger.info("[test feedback]:{}-{}-{}-{}",httpRequest.getParameter("n"),httpRequest.getParameter("c"),httpRequest.getParameter("t"),httpRequest.getParameter("p"));
		return new CaptchaVO("0","succ");
	}
}
